package com.buaa.aiguangxi.config;

import com.buaa.aiguangxi.service.UserService;
import com.buaa.aiguangxi.utils.JwtTokenUtil;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.authentication.AuthenticationManager;
import org.springframework.security.authentication.UsernamePasswordAuthenticationToken;
import org.springframework.security.core.context.SecurityContextHolder;
import org.springframework.security.web.authentication.www.BasicAuthenticationFilter;

import javax.servlet.FilterChain;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.util.ArrayList;

public class JWTAuthorizationFilter extends BasicAuthenticationFilter {
    @Autowired
    UserService userService;
    public JWTAuthorizationFilter(AuthenticationManager authenticationManager){super(authenticationManager);}
    @Override
    protected void doFilterInternal(HttpServletRequest request, HttpServletResponse response, FilterChain chain) throws IOException, ServletException {
        String tokenHeader=request.getHeader(JwtTokenUtil.TOKEN_HEADER);
        if (tokenHeader!=null&&!JwtTokenUtil.isExpiration(tokenHeader.replace(JwtTokenUtil.TOKEN_PREFIX,""))){
            SecurityContextHolder.getContext().setAuthentication(getAuthentication(tokenHeader));
        }
        if (tokenHeader==null||!tokenHeader.startsWith(JwtTokenUtil.TOKEN_PREFIX)){
            chain.doFilter(request,response);
            return;
        }

    }
    private UsernamePasswordAuthenticationToken getAuthentication(String tokenHeader){
        String token = tokenHeader.replace(JwtTokenUtil.TOKEN_PREFIX,"");
        String username = JwtTokenUtil.getUserName(token);
        String userid=JwtTokenUtil.getUserId(token);
        if(username != null){
            UsernamePasswordAuthenticationToken token1=new UsernamePasswordAuthenticationToken(username,null,new ArrayList<>());
            token1.setDetails(userid);
            return token1;
        }
        return null;
    }
}
